package com.ropeok.controller;

import com.auth0.jwt.interfaces.DecodedJWT;

import com.ropeok.Result.Result;
import com.ropeok.Utils.JwtUtils;
import com.ropeok.Utils.RedisUtil;
import com.ropeok.dto.UserLoginDto;
import com.ropeok.dto.UserDto;
import com.ropeok.entity.User;
import com.ropeok.mapper.UserDtoMapper;
import com.ropeok.service.UserLoginService;
import com.ropeok.service.serviceimpl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserLoginService userLoginService;

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private UserDtoMapper userMapper;

    @GetMapping("/login")
    public Result login(UserLoginDto userdto) {
        log.info("用户名：{}", userdto.getUsername());
        log.info("password: {}", userdto.getPassword());
        HashMap<String,Object> map=new HashMap<>();
        UserDto login = userLoginService.login(userdto);
        if(login!=null){
            UserDto user=jwtUtils.setTime(login);
            redisUtil.saveValue(String.valueOf(user.getUserid()),user,30, TimeUnit.MINUTES);
            String token=userLoginService.CreateToken(user);
            map.put("token", token);
            return Result.success(map);
        }else {
            return Result.error("登录失败，请重新登录");
        }
    }

    @GetMapping(value = "/userlist")
    @ResponseBody
    public Result UserList(){
        List<User> list = userService.FindUser();
        return new Result().success(list);
    }

    @PostMapping(value ="/add")
    public Result SaveUser(User user){
        userService.SaveUser(user);
        return Result.success();
    }

    @PostMapping("/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = (DecodedJWT) JwtUtils.verify(token);
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);

        //TODO 业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "请求成功");
        return map;
    }



}
